import './system-monitor.less'
import {onBeforeUnmount, onMounted, reactive, SimpleFunction, useRefs} from "plain-design-composition";
import {PlCol, PlDate, PlLoading, PlRow} from "plain-design";
import React from "react";
import {SystemMonitorCard} from "./system-monitor-card";
import {MicroLibService} from "@/micro/utils/MicroLibService";
import {zeroize} from "plain-utils/string/zeroize";
import {designProPage} from "../../designProPage";

export default designProPage(() => {

    const exceptionData = (() => {
        const labels = [
            {
                name: '脚本异常',
                color: '#544bd7',
                data: [] as number[],
            },
            {
                name: '网络异常',
                color: '#88bd70',
                data: [] as number[],
            },
            {
                name: '资源异常',
                color: '#f3d9b0',
                data: [] as number[],
            },
            {
                name: '渲染异常',
                color: '#f89897',
                data: [] as number[],
            },
            {
                name: '异常页面',
                color: '#eb2e95',
                data: [] as number[],
            },
        ]
        labels.forEach(item => item.data = new Array(7).fill(null).map(() => Math.ceil(Math.random() * 40) + 5))
        return labels
    })();

    const {refs, onRef} = useRefs({
        visitEl: HTMLDivElement,
        activeEl: HTMLDivElement,
        exceptionEl: HTMLDivElement,
        feedbackEl: HTMLDivElement,
        systemLoadEl: HTMLDivElement,
    })

    const state = reactive({
        currentTime: (() => {
            const nowTime = () => PlDate.today().format('HH时mm分ss秒')
            let clear: SimpleFunction;
            onMounted(() => {
                const timer = setInterval(() => state.currentTime = nowTime(), 1000)
                clear = () => clearInterval(timer)
            })
            onBeforeUnmount(() => !!clear && clear())
            return nowTime()
        })(),
    })

    const charts = {
        renderVisitChart: async () => {

            const data = (() => {
                const labels = new Array(24).fill(null).map((_, i) => zeroize(i) + '时')
                const uvList = labels.map(() => Math.ceil(Math.random() * 150) + 100)
                const pvList = uvList.map(() => Math.ceil(Math.random() * 1000))
                return {
                    labels,
                    uvList,
                    pvList,
                }
            })();

            const echarts = await MicroLibService.load.echarts()
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    }
                },
                grid: {
                    left: '1%',
                    right: '2%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        data: data.labels
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        splitLine: {show: false},
                    }
                ],
                series: [
                    {
                        name: 'Line 2',
                        type: 'line',
                        stack: '总量',
                        smooth: true,
                        lineStyle: {
                            width: 0
                        },
                        showSymbol: false,
                        areaStyle: {
                            opacity: 0.8,
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: 'rgba(0, 221, 255)'
                            }, {
                                offset: 1,
                                color: 'rgba(77, 119, 255)'
                            }])
                        },
                        emphasis: {
                            focus: 'series'
                        },
                        data: data.uvList
                    },
                    {
                        name: 'Line 3',
                        type: 'line',
                        stack: '总量',
                        smooth: true,
                        lineStyle: {
                            width: 0
                        },
                        showSymbol: false,
                        areaStyle: {
                            opacity: 0.8,
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: 'rgba(55, 162, 255)'
                            }, {
                                offset: 1,
                                color: 'rgba(116, 21, 219)'
                            }])
                        },
                        emphasis: {
                            focus: 'series'
                        },
                        data: data.uvList
                    },
                ]
            };
            const ins = echarts.init(refs.visitEl!)
            ins.setOption(option)
        },
        renderActiveChart: async () => {
            const echarts = await MicroLibService.load.echarts()
            const option = {
                legend: {
                    top: 'bottom'
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: {show: true},
                        dataView: {show: true, readOnly: false},
                        restore: {show: true},
                        saveAsImage: {show: true}
                    }
                },
                series: [
                    {
                        name: '面积模式',
                        type: 'pie',
                        radius: [0, 50],
                        center: ['50%', '50%'],
                        roseType: 'area',
                        itemStyle: {
                            borderRadius: 8
                        },
                        data: ['活跃用户', '静默用户', '留存用户', '跳出用户', '潜在客户', '真实客户'].map(name => ({
                            name,
                            value: Math.ceil(Math.random() * 100) + 10
                        }))
                    }
                ]
            };
            const ins = echarts.init(refs.activeEl)
            ins.setOption(option)
        },
        renderExceptionChart: async () => {
            const echarts = await MicroLibService.load.echarts()
            const option = {
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    top: '2%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                },
                yAxis: {
                    type: 'value',
                    splitLine: {show: false}
                },
                series: exceptionData.map((data) => ({
                    name: data.name,
                    type: 'line',
                    data: data.data,
                    smooth: true,
                    lineStyle: {color: data.color},
                })),
            };
            const ins = echarts.init(refs.exceptionEl)
            ins.setOption(option)
        },
        renderFeedbackChart: async () => {
            const echarts = await MicroLibService.load.echarts()
            const option = {
                series: [
                    {
                        type: 'pie',
                        selectedMode: 'single',
                        radius: [0, '40%'],
                        label: {
                            position: 'inner',
                            fontSize: 10,
                        },
                        data: [
                            {value: 1548, name: '好评'},
                            {value: 775, name: '差评'},
                            {value: 679, name: '无所谓'}
                        ]
                    },
                    {
                        type: 'pie',
                        radius: ['50%', '65%'],
                        labelLine: {
                            length: 30,
                        },
                        data: [
                            {value: 1048, name: '功能简单易用'},
                            {value: 335, name: '主题美观'},
                            {value: 310, name: '辨识度高'},
                            {value: 251, name: '操作流畅'},
                            {value: 234, name: 'BUG很多'},
                            {value: 147, name: '页面卡顿'},
                            {value: 135, name: '经常报错'},
                            {value: 102, name: '无响应'}
                        ]
                    }
                ]
            };
            const ins = echarts.init(refs.feedbackEl)
            ins.setOption(option)
        },
        renderSystemLoadChart: async () => {
            const echarts = await MicroLibService.load.echarts()
            const option = {
                series: [{
                    type: 'gauge',
                    radius: '100%',
                    axisLine: {
                        lineStyle: {
                            width: 30,
                            color: [
                                [0.2, 'rgba(55, 162, 255)'],
                                [0.5, 'rgba(77, 119, 255)'],
                                [0.8, 'rgba(116, 21, 219)'],
                                [1, 'rgba(254, 113, 111)'],
                            ]
                        }
                    },
                    /*刻度小分隔线*/
                    axisTick: {
                        distance: -30,
                        length: 8,
                        lineStyle: {
                            color: '#fff',
                            width: 2
                        }
                    },
                    /*刻度大分隔线*/
                    splitLine: {
                        distance: -30,
                        length: 30,
                        lineStyle: {
                            color: '#fff',
                            width: 4
                        }
                    },
                    /*刻度文本*/
                    axisLabel: {
                        color: 'auto',
                        distance: 40,
                        fontSize: 10
                    },
                    detail: {
                        valueAnimation: true,
                        formatter: (val: number) => {
                            if (val > 80) {
                                return '高负载运行'
                            }
                            if (val > 20) {
                                return '正常运行'
                            }
                            if (val > 0) {
                                return '资源冗余'
                            }
                        },
                        color: 'auto',
                        fontSize: '14',
                    },
                    data: [{
                        value: 70
                    }]
                }]
            };
            const ins = echarts.init(refs.systemLoadEl)
            ins.setOption(option)

            setInterval(function () {
                option.series[0].data[0].value = (Math.random() * 100).toFixed(2) as any - 0;
                ins.setOption(option, true);
            }, 2000);
        }
    }

    onMounted(() => {
        Object.values(charts).forEach(i => i())
    })

    return () => (
        <div className="system-monitor">
            <PlRow gutter={24}>
                <PlCol span={6}>
                    <SystemMonitorCard
                        title={'访问人数'}
                        icon={'el-icon-position'}
                        iconColor={'primary'}
                        number={'201'} desc={"近30天访问人数"} caret={"top"} caretStatus={"success"} percent={"32.10%"}/>
                </PlCol>
                <PlCol span={6}>
                    <SystemMonitorCard
                        title={'点击数量'}
                        icon={'el-icon-thumb'}
                        iconColor={'success'}
                        number={'1,671'} desc={"近30天点击量"} caret={"top"} caretStatus={"success"} percent={"87.77%"}/>
                </PlCol>
                <PlCol span={6}>
                    <SystemMonitorCard
                        title={'到达数量'}
                        icon={'el-icon-place'}
                        iconColor={'warn'}
                        number={'1,150'} desc={"近30天到达量"} caret={"bottom"} caretStatus={"error"} percent={"12.51%"}/>
                </PlCol>
                <PlCol span={6}>
                    <SystemMonitorCard
                        title={'停留时长'}
                        icon={'el-icon-alarm-clock'
                        } iconColor={'error'}
                        number={'984'} desc={"转化率"} caret={"bottom"} caretStatus={"error"} percent={"20.97%"}/>
                </PlCol>
            </PlRow>
            <PlRow gutter={24}>
                <PlCol span={18}>
                    <SystemMonitorCard icon="el-icon-share" iconColor={'rgb(109,149,246)'} title={"近一小时访问量"} showMore={false} bodyPadding={false}>
                        {{
                            default: <div className="one-hour-visit-chart" ref={onRef.visitEl}/>,
                            headRight: (
                                <div className="system-chart-indicator">
                                    <div className="system-chart-indicator-item" style={{color: 'rgba(116, 21, 219)'}}>
                                        浏览量(PV)
                                    </div>
                                    <div className="system-chart-indicator-item" style={{color: 'rgba(0, 221, 255)'}}>
                                        到达量(PV)
                                    </div>
                                </div>
                            )
                        }}
                    </SystemMonitorCard>
                </PlCol>
                <PlCol span={6}>
                    <SystemMonitorCard className="current-online-card" title={'当前在线'} icon="el-icon-s-custom" iconColor="#73D13D" showMore={false}>
                        <div className="current-online-card-body">
                            <div className="current-online-card-now-time">{state.currentTime}</div>
                            <div className="system-monitor-big-number">233</div>
                            <div className="current-online-card-desc">在线用户数</div>
                            <div className="current-online-card-loading">
                                <PlLoading type="delta" status="primary"/>
                                <span>每秒更新</span>
                            </div>
                        </div>
                    </SystemMonitorCard>
                    <SystemMonitorCard className="active-analysis-card" title="活跃度" icon="el-icon-s-opportunity" iconColor="#eb2f95" showMore={false}>
                        <div className="active-analysis-card-chart" ref={onRef.activeEl}/>
                    </SystemMonitorCard>
                </PlCol>
            </PlRow>
            <PlRow gutter={24}>
                <PlCol span={12}>
                    <SystemMonitorCard className="" title="异常监控" icon="el-icon-s-comment" iconColor="#ffc53c" showMore={false}>
                        {{
                            default: <div className="average-comment-chart" ref={onRef.exceptionEl}/>,
                            headRight: (
                                <div className="system-chart-indicator">
                                    {exceptionData.map((item, index) => (
                                        <div key={index} className="system-chart-indicator-item" style={{color: item.color}}>
                                            {item.name}
                                        </div>
                                    ))}
                                </div>
                            )
                        }}
                    </SystemMonitorCard>
                </PlCol>
                <PlCol span={6}>
                    <SystemMonitorCard className="" title="客户反馈" icon="el-icon-star-on" iconColor="#597ef7" showMore={false}>
                        <div className="user-feedback-chart" ref={onRef.feedbackEl}/>
                    </SystemMonitorCard>
                </PlCol>
                <PlCol span={6}>
                    <SystemMonitorCard className="" title="系统负载" icon="el-icon-place" iconColor="#ff9696" showMore={false}>
                        <div className="system-load-chart" ref={onRef.systemLoadEl}/>
                    </SystemMonitorCard>
                </PlCol>
            </PlRow>
        </div>
    )
})